﻿using smforj.common.model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Telerik.WinControls;
using Telerik.WinControls.Primitives;
using Telerik.WinControls.UI;

namespace MonitorEquipmentFrm.View
{
    public partial class FittingShow : Telerik.WinControls.UI.ShapedForm
    {

        //private int columnIDCounter = 0;
        private const int OleHeaderSize = 78;
        private Font segoeFont = new Font("Segoe UI", 8.25f, FontStyle.Regular);
        private Font buttonFont = new Font("Segoe UI", 9f, FontStyle.Bold);
        //初始化DataSource
        private DataTable dt = null;

        private String[] columnNames = new String[10] { 
            "ID", "ProductName", "Photo1", "Photo2", "Photo3", "Photo4", "Photo5", "Photo6","Type", "Remark"
        };

        private BackgroundWorker worker = new BackgroundWorker();

        public FittingShow()
        {
            InitializeComponent();

            worker.DoWork +=worker_DoWork;

            dt = CreateDataTable();
            this.Shape = new RoundRectShape(7);
            this.BorderWidth = 1;
            this.radGridView1.TableElement.RowHeight = 120;

            //this.radGridView1.RowsChanging += new GridViewCollectionChangingEventHandler(radGridView1_RowsChanging);
            this.radGridView1.DefaultValuesNeeded += new GridViewRowEventHandler(radGridView1_DefaultValuesNeeded);
            this.radGridView1.CurrentRowChanged +=radGridView1_CurrentRowChanged; 
        }

        private Boolean IsShowInfo = true;
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (IsShowInfo)
            { 
                InitData();
                //5秒钟刷新一次
                Thread.Sleep(1000 * 5);
            }
        }

        public delegate void CB_SetDataGridViewInfo(RadGridView dgvr);
        public void Deg_SetDataGridViewInfo(RadGridView dgvr)//委托的方法
        {
            if (this.radGridView1.InvokeRequired)
            {
                CB_SetDataGridViewInfo cs = new CB_SetDataGridViewInfo(Deg_SetDataGridViewInfo);
                this.BeginInvoke(cs, new object[] { dgvr });
            }
            else
            {
                UpdatePanelInfo(this.radGridView1.CurrentRow);
            }
        }
        private void radGridView1_CurrentRowChanged(object sender, CurrentRowChangedEventArgs e)
        {
            Deg_SetDataGridViewInfo(this.radGridView1);
            //UpdatePanelInfo(this.radGridView1.CurrentRow);
        }

        #region 显示搭配信息
        private void radGridView1_DefaultValuesNeeded(object sender, GridViewRowEventArgs e)
        {
            Deg_SetDataGridViewInfo(this.radGridView1);
            //UpdatePanelInfo(this.radGridView1.CurrentRow);
        }
         
        private void UpdatePanelInfo(GridViewRowInfo currentRow)
        { 
            if (currentRow != null && !(currentRow is GridViewNewRowInfo))
            {
                this.lbRemark.Text = this.GetSafeString(currentRow.Cells[columnNames[9]].Value);
                object photoValue = currentRow.Cells[columnNames[7]].Value;

                if (!Convert.IsDBNull(photoValue) && photoValue != null)
                {
                    Image image = null;
                    if (photoValue is Bitmap)
                    {
                        Bitmap bm = (Bitmap)photoValue;
                        image = Image.FromHbitmap(bm.GetHbitmap());
                    }
                    else if (photoValue is String)
                    {
                        image = this.LoadImage((String)photoValue);
                    }
                    if (image != null) 
                        this.radPanel2.BackgroundImage = new Bitmap(image); 
                }
                else
                {
                    this.radPanel2.BackgroundImage = new Bitmap(10, 10);
                }
                this.radPanel2.BackgroundImageLayout = ImageLayout.Stretch;
            }
            else
            { 
                this.radPanel2.BackgroundImage = new Bitmap(10, 10);
                this.lbRemark.Text = "";
            }
        }


        private string GetSafeString(object value)
        {
            if (value == null)
            {
                return string.Empty;
            }

            return value.ToString();
        }

        #endregion
        /// <summary>
        /// 创建数据对象
        /// </summary>
        /// <returns></returns>
        private DataTable CreateDataTable()
        {
            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn();
            dc.ColumnName = columnNames[0];
            dc.DataType = typeof(String);
            dt.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = columnNames[1];
            dc.DataType = typeof(String);
            dt.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = columnNames[2];
            dc.DataType = typeof(Image);
            dt.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = columnNames[3];
            dc.DataType = typeof(Image);
            dt.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = columnNames[4];
            dc.DataType = typeof(Image);
            dt.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = columnNames[5];
            dc.DataType = typeof(Image);
            dt.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = columnNames[6];
            dc.DataType = typeof(Image);
            dt.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = columnNames[7];
            dc.DataType = typeof(Image);
            dt.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = columnNames[8];
            dc.DataType = typeof(String);
            dt.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = columnNames[9];
            dc.DataType = typeof(String);
            dt.Columns.Add(dc); 
            return dt;
        }


        private void InitData()
        {
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                    dt.Rows.Clear();
                List<Collocation> list = GlobalCache.colList.FindAll(z => z.Loaction == "1");
                foreach (Collocation col in list)
                {
                    DataRow newRow = dt.NewRow();
                    newRow[0] = col.ID;
                    newRow[1] = col.Name;
                    //if (!String.IsNullOrEmpty(col.Image1))
                    //    newRow[2] = this.LoadImage(Assembly.GetExecutingAssembly().GetName().Name + ".View.Images.data." + col.Image1);
                    //if (!String.IsNullOrEmpty(col.Image2))
                    //    newRow[3] = this.LoadImage(Assembly.GetExecutingAssembly().GetName().Name + ".View.Images.data." + col.Image2);
                    //if (!String.IsNullOrEmpty(col.Image3))
                    //    newRow[4] = this.LoadImage(Assembly.GetExecutingAssembly().GetName().Name + ".View.Images.data." + col.Image3);
                    //if (!String.IsNullOrEmpty(col.Image4))
                    //    newRow[5] = this.LoadImage(Assembly.GetExecutingAssembly().GetName().Name + ".View.Images.data." + col.Image4);
                    //if (!String.IsNullOrEmpty(col.Image5))
                    //    newRow[6] = this.LoadImage(Assembly.GetExecutingAssembly().GetName().Name + ".View.Images.data." + col.Image5);
                    //if (!String.IsNullOrEmpty(col.Image6))
                    //    newRow[7] = this.LoadImage(Assembly.GetExecutingAssembly().GetName().Name + ".View.Images.data." + col.Image6);
                    newRow[8] = col.RFID;
                    newRow[9] = col.Remark;
                    dt.Rows.Add(newRow);
                } 
            } 
        }

        private void FittingShow_Load(object sender, EventArgs e)
        {
            this.radGridView1.DataSource = dt;

            this.BackgroundImage = this.LoadImage(Assembly.GetExecutingAssembly().GetName().Name + ".View.Images.bg.png");
            this.BackgroundImageLayout = ImageLayout.Stretch;

            this.radPanel2.BackgroundImage = this.LoadImage(Assembly.GetExecutingAssembly().GetName().Name + ".View.Images.f1.PNG");
            this.radTitleBar1.BackgroundImage = this.LoadImage(Assembly.GetExecutingAssembly().GetName().Name + ".View.Images.logoCH.png");
            this.radTitleBar1.BackgroundImageLayout = ImageLayout.Center;
            ((TextPrimitive)this.radTitleBar1.TitleBarElement.Children[2].Children[1]).Text = String.Empty;
            ((ImagePrimitive)this.radTitleBar1.TitleBarElement.Children[2].Children[0]).Image = null;


            RoundRectShape panelShapeTopRounded = new RoundRectShape(3);
            panelShapeTopRounded.BottomRightRounded = false;
            panelShapeTopRounded.BottomLeftRounded = false;
            radPanel4.PanelElement.Shape = panelShapeTopRounded;

            RoundRectShape panelShapeBottomRounded = new RoundRectShape(3);
            panelShapeBottomRounded.TopLeftRounded = false;
            panelShapeBottomRounded.TopRightRounded = false;
            radPanel1.PanelElement.Shape = panelShapeBottomRounded;

            radPanel3.PanelElement.Shape = panelShapeTopRounded;
             
            radLabel2.Font = segoeFont;
            lbRemark.Font = segoeFont;  

            this.radGridView1.TableElement.Padding = new Padding(0);
            this.radGridView1.TableElement.DrawBorder = false;
            this.radGridView1.TableElement.CellSpacing = -1;
            this.radGridView1.TableElement.Text = "";

            this.radGridView1.MasterTemplate.BestFitColumns();
            this.radGridView1.Columns[columnNames[0]].Width = 120;
            //this.radGridView1.Columns[columnNames[0]].IsVisible = true;
            this.radGridView1.Columns[columnNames[1]].Width = 120;
            //this.radGridView1.Columns[columnNames[1]].IsVisible = false;

            this.radGridView1.Columns[columnNames[2]].Width = 150;
            this.radGridView1.Columns[columnNames[3]].Width = 150;
            this.radGridView1.Columns[columnNames[4]].Width = 150;
            this.radGridView1.Columns[columnNames[5]].Width = 150;
            this.radGridView1.Columns[columnNames[6]].Width = 150;
            this.radGridView1.Columns[columnNames[7]].Width = 150;
            this.radGridView1.Columns[columnNames[7]].IsVisible = false;

            this.radGridView1.Columns[columnNames[8]].IsVisible = false;

            this.radGridView1.Columns[columnNames[9]].Width = 200;

            //InitData();
            //加载数据信息
            worker.RunWorkerAsync();

            this.radGridView1.Refresh();
            //this.FillComboBox();
            this.UpdatePanelInfo(this.radGridView1.CurrentRow);

            this.WindowState = FormWindowState.Maximized;
        }


        #region Image
        private Image LoadImage(string name)
        {
            Stream stream = Assembly.GetAssembly(this.GetType()).GetManifestResourceStream(name);

            if (stream == null)
            {
                throw new NullReferenceException("Cannot find " + name);
            }

            return new Bitmap(stream);
        }

        private Image GetImageFromBytes(byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
            {
                return null;
            }

            Image result = null;
            MemoryStream stream = null;

            try
            {
                int count;
                int start;

                if (IsOleContainer(bytes))
                {
                    count = bytes.Length - OleHeaderSize;
                    start = OleHeaderSize;
                }
                else
                {
                    count = bytes.Length;
                    start = 0;
                }

                stream = new MemoryStream(bytes, start, count);
                result = Image.FromStream(stream);
            }
            catch
            {
                result = null;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
            return result;
        }
        private bool IsOleContainer(byte[] imageData)
        {
            return (imageData != null
                && imageData[0] == 0x15
                && imageData[1] == 0x1C);
        }
        #endregion

        private void FittingShow_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.IsShowInfo = false;
            worker = null;
        }


    }
}
